'''
Author: StormAX 724456475@qq.com
Date: 2024-03-22 10:05:44
LastEditors: StormAX 724456475@qq.com
LastEditTime: 2024-03-22 20:21:50
FilePath: \debug_client\data_serve\client.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
import zmq
import json
from data_serve import trace_format, cmd_map
# import cmd_map
import threading
import time

def cmd_str(iCmd, mCmd):
    if iCmd in mCmd:
        return mCmd[iCmd]
    else:
        return hex(iCmd)


bus_ch = ["client_in", "client_out", "mousectrl_in", "mousectrl_out", "dbcenter_in", "dbcenter_out"]

def format_json(json_obj: dict):
    json_obj["CMD"] = hex(json_obj["CMD"])
            
    if "tracing" in json_obj:
        json_obj["tracing"] = trace_format.format(json_obj["tracing"])
        
    msg_list = json_obj["MSG"]
    for msg in msg_list:
        if msg["content"] is None: continue
        if "cmd" in msg["content"]:
            if msg["channel"] in bus_ch:
                msg["content"]["cmd"] = cmd_str(msg["content"]["cmd"], cmd_map.mBusCmd)
            elif msg["channel"] == "api_out":
                if msg["api_type"] == "hisi":
                    msg["content"]["cmd"] = cmd_str(msg["content"]["cmd"], cmd_map.mHisiCmd)
            else:
                msg["content"]["cmd"] = hex(msg["content"]["cmd"])
    json_obj["MSG"] = msg_list
            
    return json_obj


def msg_loop(ip):
    context = zmq.Context()

    socket = context.socket(zmq.SUB)
    socket.setsockopt_string(zmq.SUBSCRIBE, '')
    socket.connect(f"tcp://{ip}:9776")

    received_chunks = []
    i=0
    while True:
        print("listening...")
        chunk = socket.recv_string()
        received_chunks.append(chunk)
        if not socket.getsockopt(zmq.RCVMORE):
            assembled_message = ''.join(received_chunks).replace("[debug]", "", 1)
            json_obj = json.loads(assembled_message)
            debug_id = json_obj["debug_id"]
            process = json_obj["PROCESS"]
            with open(f"log/{debug_id}.json", "a") as f:
                json_obj = format_json(json_obj)
                json_str = json.dumps(json_obj)
                f.write(json_str + '\n')
            received_chunks.clear()
            i += 1
            
            
# msg_loop("172.10.42.19")
